//
//  ShopListViewController.m
//  WHB_driver
//
//  Created by 徐国庆 on 15/12/8.
//  Copyright (c) 2015年 turing. All rights reserved.
//

#import "ShopListViewController.h"
#import "shipListCell.h"
#import "shipDetailViewController.h"
#import "shopListVCCell.h"
#import "historyListCell.h"
#import "receiveShipOverViewController.h"
#import "CWStarRateView.h"
#import "FVCustomAlertView.h"
#import "landingViewController.h"
#import "User.h"
#import "OrderModel.h"

@interface ShopListViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UIAlertViewDelegate>

@property(nonatomic, strong) UITableView    *tableView;
@property(nonatomic, strong) UIButton       *currentButton;
@property(nonatomic, strong) UIButton       *hisButton;
@property(nonatomic, strong) UILabel        *chooseLine;
@property(nonatomic, assign) BOOL           oneOrTwo;
@property(nonatomic, strong) CWStarRateView *ratingControl;
@property(nonatomic, strong) User           *user;
@property(nonatomic, strong) NSMutableArray *sourceArr;

@end

@implementation ShopListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.sourceArr = [NSMutableArray new];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //取得用户信息
    self.user = (User *)[NSKeyedUnarchiver unarchiveObjectWithFile:kUserPath];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navtitle.text = @"货单";
    self.leftButton.hidden = YES;
    [self initWithView];
    self.oneOrTwo = NO;
    UIView *view = [self headerView];
    view.frame = CGRectMake(0, kNavHeight + kStateHeight, kUIScreenWidth, 80);
    [self.view addSubview:view];
    [self getDriverCurOrder];
//    [self getDriverHisOrder];
}


#pragma mark UITabelViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!_oneOrTwo) {
        OrderModel *order = [self.sourceArr objectAtIndex:indexPath.row];
        // 当前货单
        NSString * indentifer = @"shipList";
        
        shopListVCCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer];
        if (cell == nil) {
            cell = [[shopListVCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifer];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.backgroundColor = [UIColor HexStrWithColor:@"eeeeee"];
        cell.vechileNumberLabel.text = self.user.licensePlate;//@"粤1234A";
        cell.vechileNameLabel.text = self.user.brandName;//@"东风多利卡";
        
        cell.shipListNumberLabel.text = [NSString stringWithFormat:@"货单号:%@", order.orderNo];//@"货单号:12345678";
        cell.shipListNumberLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.stateLabel.text = order.orderStatus;//@"取货中";
        cell.stateLabel.textColor = [UIColor HexStrWithColor:@"ff6600"];
        cell.line1.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.setoutAddressLabel.text = order.startAddressName;//@"深圳";
        cell.addressImageView.image = [UIImage imageNamed:@"icon_Cargo_to"];
        cell.aimAddressLabel.text = order.endAddressName;//@"上海";
        cell.mediumImageView.image = [UIImage imageNamed:@"icon_Cargo_cargo"];
        cell.mediumLabel.text = order.mediumName;//@"汽油";
        cell.weightImageView.image = [UIImage imageNamed:@"icon_Cargo_car"];
        cell.weightLabel.text = order.weight;//@"21吨";
        cell.receiveShipOverButton.backgroundColor = [UIColor HexStrWithColor:@"f8cc00"];
        //    [cell.receiveShipOverButton setImage:[UIImage imageNamed:@"icon_Button_received"] forState:UIControlStateNormal];
        //    [cell.receiveShipOverButton setImageEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 65)];
        [cell.receiveShipOverButton addTarget:self action:@selector(receiveShipOverButtonAction:) forControlEvents:UIControlEventTouchDown];
        cell.receiveShipOverButton.tag = 100 +indexPath.row;
        cell.line2.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.receiveBusinessLabel.text = @"取货方";
        cell.receiveBusinessLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.receiveContentLabel.text = order.getOrgName;//@"中广核";
        cell.identificationImageView.image = [UIImage imageNamed:@"btn_icon_Confirmed_normal"];
        cell.callingButton.backgroundColor = [UIColor HexStrWithColor:@"f8cc00"];
        //    [cell.callingButton setImage:[UIImage imageNamed:@"icon_Mine_phone"] forState:UIControlStateNormal];
        //    [cell.callingButton setImageEdgeInsets:UIEdgeInsetsMake(5, 10, 5, 65)];
        [cell.callingButton addTarget:self action:@selector(callingButtonAction:) forControlEvents:UIControlEventTouchDown];
        cell.callingButton.tag = 200 + indexPath.row;
        cell.line3.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.receiveDateLabel.text = @"取货日期";
        cell.receiveDateLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.receiveDateContentLabel.text = order.loadGoodsTime;//@"2015-10-07";
        cell.line4.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.receiveAddressLabel.text = @"取货地址";
        cell.receiveAddressLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.receiveAddressContentLabel.text = order.getGoodsAddress;//@"广东省深圳市南山北环大道";
        cell.line5.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.remarkLabel.text = @"备注";
        cell.remarkLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.remarkContentLabel.text = order.note;//@"上午 早点来取货";
        return cell;
    } else {
        // 历史货单
        OrderModel *order = [self.sourceArr objectAtIndex:indexPath.row];
        NSString * indentifer = @"historyListCell";
        
        historyListCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifer];
        if (cell == nil) {
            cell = [[historyListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifer];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.topLabel.backgroundColor = [UIColor HexStrWithColor:@"eeeeee"];
        cell.shipListNumberLabel.text = [NSString stringWithFormat:@"货单号:%@", order.orderNo];
        cell.shipListNumberLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.stateLabel.text = order.orderStatus;
        cell.stateLabel.textColor = [UIColor HexStrWithColor:@"ff6600"];
        cell.line1.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.setoutAddressLabel.text = order.startAddressName;
        cell.addressImageView.image = [UIImage imageNamed:@"icon_Cargo_to"];
        cell.aimAddressLabel.text = order.endAddressName;
        cell.mediumImageView.image = [UIImage imageNamed:@"icon_Cargo_cargo"];
        cell.mediumLabel.text = order.mediumName;//@"汽油";
        cell.weightImageView.image = [UIImage imageNamed:@"icon_Cargo_car"];
        cell.weightLabel.text = [NSString stringWithFormat:@"%@吨", order.weight];//@"21吨";
        cell.signInLabel.text = order.orderStatus;//@"已签收";
        cell.signInLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.line2.backgroundColor = [UIColor HexStrWithColor:@"999999"];
        
        cell.remarkLabel.text = @"备注";
        cell.remarkLabel.textColor = [UIColor HexStrWithColor:@"999999"];
        cell.remarkContentLabel.text = order.note;//@"上午 早点来取货";
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.oneOrTwo) {
        
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, 250, 85)];
        
        self.ratingControl = [[CWStarRateView alloc]initWithFrame:CGRectMake((bottomView.frame.size.width - 120) / 2, 0, 120, 25)];
        self.ratingControl.scorePercent = 0.6;
        self.ratingControl.hasAnimation = YES;
        [bottomView addSubview:self.ratingControl];
        
        UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 250, 0.5)];
        lineLabel.backgroundColor = [UIColor HexStrWithColor:@"cccccc"];
        [bottomView addSubview:lineLabel];
        
        UIButton *commitButton = [UIButton buttonWithType:UIButtonTypeCustom];
        commitButton.frame = CGRectMake((bottomView.frame.size.width - 100) / 2, CGRectGetMaxY(lineLabel.frame) + 10, 100, 30);
        [commitButton setTitle:@"提交" forState:UIControlStateNormal];
        [commitButton setTitleColor:[UIColor HexStrWithColor:@"ff6600"] forState:UIControlStateNormal];
        [bottomView addSubview:commitButton];
        [commitButton addTarget:self action:@selector(commitButtonAction:) forControlEvents:UIControlEventTouchDown];
        
        [FVCustomAlertView showAlertOnView:self.view withTitle:@"请对此次服务货主进行打分" titleColor:[UIColor blackColor] width:250 height:130 blur:NO backgroundImage:nil backgroundColor:[UIColor whiteColor] cornerRadius:5 shadowAlpha:0.2 alpha:1 contentView:bottomView type:FVAlertTypeCustom allowTap:YES];
        
    } else{
        OrderModel *order = [self.sourceArr objectAtIndex:indexPath.row];
        [DataController getOrderDetail:[NSNumber numberWithLong:order.orderId]
                                userId:[NSNumber numberWithLong:self.user.userId]
                              userType:@"3"
                                  imei:kIdentifierString
                             withBlock:^(NSDictionary *result) {
                                 NSLog(@"result =？？？= %@", result);
                                 if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                     NSDictionary *data = [result objectForKey:@"data"];
                                      OrderModel *order = [MTLJSONAdapter modelOfClass:[OrderModel class] fromJSONDictionary:data error:nil];
                                     shipDetailViewController *shipDetailVC = [[shipDetailViewController alloc] initWithOrder:order];
                                     [self.navigationController pushViewController:shipDetailVC animated:YES];
                                 } else if ([[result objectForKey:@"resCode"] isEqualToString:@"2"]){
                                     NSLog(@"踢掉前一用户");
                                 }
                             }];
    }
}

- (void)commitButtonAction:(UIButton *)button{
    NSLog(@"%f", self.ratingControl.scorePercent);
    [FVCustomAlertView hideAlertFromView:self.view fading:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.oneOrTwo) {
        // 历史货单
        return 150;
    } else{
        // 当前货单
        return 350;
    }
}

#pragma mark 当前货单
- (void)currentButtonAction:(UIButton *)button{
    [self.currentButton setTitleColor:[UIColor HexStrWithColor:@"EA0000"] forState:UIControlStateNormal];
    [self.hisButton setTitleColor:[UIColor HexStrWithColor:@"999999"] forState:UIControlStateNormal];
    
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.chooseLine.frame = CGRectMake(20, 38, kUIScreenWidth / 2 - 40, 2);
    } completion:^(BOOL finished) {
    }];
    self.oneOrTwo = NO;
    [self.tableView reloadData];
    [self getDriverCurOrder];
}

#pragma mark 历史货单
- (void)hisButtonAction:(UIButton *)button{
    self.tableView.contentOffset = CGPointMake(0, 0);
    [self.currentButton setTitleColor:[UIColor HexStrWithColor:@"999999"] forState:UIControlStateNormal];
    [self.hisButton setTitleColor:[UIColor HexStrWithColor:@"EA0000"] forState:UIControlStateNormal];
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:5 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.chooseLine.frame = CGRectMake(kUIScreenWidth / 2 + 20, 38, kUIScreenWidth / 2 - 40, 2);
    } completion:^(BOOL finished) {
    }];
    self.oneOrTwo = YES;
    [self.tableView reloadData];
    [self getDriverHisOrder];
}

#pragma mark 取货完成点击方法
- (void)receiveShipOverButtonAction:(UIButton *)button{
    
    OrderModel *order = [self.sourceArr objectAtIndex:button.tag - 100];
    receiveShipOverViewController *receiveShipOverVC = [[receiveShipOverViewController alloc] initWithOrder:order];
    [self.navigationController pushViewController:receiveShipOverVC animated:YES];
}

#pragma mark 拨打电话点击方法
- (void)callingButtonAction:(UIButton *)button{
    NSString *phoneNum = @"15146001603";
    UIWebView *callphonewebview;
    if (callphonewebview==nil) {
        callphonewebview=[[UIWebView alloc]init];
    }
    [self.view addSubview:callphonewebview];
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNum]]];
    [callphonewebview loadRequest:request];
    
   landingViewController *landingVC = [[landingViewController alloc] init];
    [self presentViewController:landingVC animated:YES completion:^{
        
    }];
}

/**
 *  头
 *
 *  @return <#return value description#>
 */
- (UIView *)headerView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kNavHeight, kUIScreenWidth, 40)];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, 0.5)];
    lineLabel.backgroundColor = [UIColor HexStrWithColor:@"313131"];
//    lineLabel.backgroundColor = [UIColor whiteColor];
    [view addSubview:lineLabel];
    
    /*
    UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth / 2, 40)];
    numberLabel.text = @"京733212";
    numberLabel.textColor = [UIColor HexStrWithColor:@"FFA042"];
    numberLabel.font = [UIFont systemFontOfSize:14];
    numberLabel.textAlignment = 1;
    [view addSubview:numberLabel];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(kUIScreenWidth / 2, 0, kUIScreenWidth / 2, 40)];
    nameLabel.text = @"东风风行";
    nameLabel.textColor = [UIColor HexStrWithColor:@"FFA042"];
    nameLabel.font = [UIFont systemFontOfSize:14];
    nameLabel.textAlignment = 1;
    [view addSubview:nameLabel];
    
    */
    
    // 当前货单
    self.currentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.currentButton.frame = CGRectMake(0, 0.5, kUIScreenWidth / 2, 40);
    [self.currentButton setTitle:@"当前货单" forState:UIControlStateNormal];
    [self.currentButton setTitleColor:[UIColor HexStrWithColor:@"EA0000"] forState:UIControlStateNormal];
    self.currentButton.titleLabel.font = [UIFont systemFontOfSize:17];
    self.currentButton.backgroundColor = [UIColor blackColor];
    [self.currentButton addTarget:self action:@selector(currentButtonAction:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:self.currentButton];
    
    //当前货单与历史货单中间的竖线
    UILabel *verticalLabel = [[UILabel alloc] initWithFrame:CGRectMake(kUIScreenWidth / 2 , 5, 0.5, 30)];
    verticalLabel.backgroundColor = [UIColor whiteColor];
    [view addSubview:verticalLabel];
    
    // 历史货单
    self.hisButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.hisButton.frame = CGRectMake(kUIScreenWidth / 2 + 0.5, 0.5, kUIScreenWidth / 2, 40);
    [self.hisButton setTitle:@"历史货单" forState:UIControlStateNormal];
    [self.hisButton setTitleColor:[UIColor HexStrWithColor:@"999999"] forState:UIControlStateNormal];
    self.hisButton.backgroundColor = [UIColor blackColor];
    [self.hisButton addTarget:self action:@selector(hisButtonAction:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:self.hisButton];
    self.hisButton.titleLabel.font = [UIFont systemFontOfSize:17];
    
    /*
    // 车牌号和车名下的线
    UILabel *downLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 39, kUIScreenWidth, 0.5)];
    downLine.backgroundColor = [UIColor HexStrWithColor:@"5B5B5B"];
    [view addSubview:downLine];
    
    */
    /*
    // 移动条下面的线
    UILabel *bottomLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 79, kUIScreenWidth, 0.5)];
    bottomLine.backgroundColor = [UIColor HexStrWithColor:@"5B5B5B"];
    [view addSubview:bottomLine];
    */
    // 移动条
    self.chooseLine = [[UILabel alloc] initWithFrame:CGRectMake(20, 38, kUIScreenWidth / 2 - 40, 2)];
    self.chooseLine.backgroundColor = [UIColor HexStrWithColor:@"EA0000"];
    [view addSubview:self.chooseLine];
    
    return view;
}

- (void)initWithView{
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavHeight + 60, kUIScreenWidth, kUIScreenHeight - kNavHeight - 90 - kStateHeight) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
//    self.tableView.backgroundColor = [UIColor HexStrWithColor:@"999999"];
    self.tableView.backgroundColor = [UIColor whiteColor];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.tableView.contentOffset.y < 0) {
        self.tableView.contentOffset = CGPointMake(0, 0);
    }
}

/**
 *  获取司机当前货单信息
 */
- (void)getDriverCurOrder{
    [DataController getDriverCurOrder:[NSNumber numberWithLong:self.user.userId]
                               userId:[NSNumber numberWithLong:self.user.userId]
                                 imei:@"B7A35836-46E2-4A58-"//kIdentifierString
                            withBlock:^(NSDictionary *result) {
                                if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                    [self.sourceArr removeAllObjects];
                                    NSLog(@"kIdentifierString == %@", kIdentifierString);
                                    NSLog(@"result ==》》》 %@", result);
                                    NSDictionary *data = [result objectForKey:@"data"];
                                    OrderModel *order = [MTLJSONAdapter modelOfClass:[OrderModel class] fromJSONDictionary:data error:nil];
                                    [self.sourceArr addObject:order];
                                }
                                [self.tableView reloadData];
                            }];
}

/**
 *  获取司机历史货单列表信息
 */
- (void)getDriverHisOrder{
    [DataController getDriverHisOrder:[NSNumber numberWithLong:self.user.userId]
                               userId:[NSNumber numberWithLong:self.user.userId]
                               lastId:[NSNumber numberWithLong:0]
                                 imei:kIdentifierString
                            withBlock:^(NSDictionary *result) {
                               
                                NSLog(@"result == %@", result);
                                if ([[result objectForKey:@"resCode"] isEqualToString:@"0"]) {
                                    NSDictionary *data = [result objectForKey:@"data"];
                                    NSArray *orderList = [data objectForKey:@"orderList"];
                                    [self.sourceArr removeAllObjects];
                                    for (NSDictionary *dic in orderList) {
                                        OrderModel *order = [MTLJSONAdapter modelOfClass:[OrderModel class] fromJSONDictionary:dic error:nil];
                                        [self.sourceArr addObject:order];
                                    }
                                    [self.tableView reloadData];
                                }
                            }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
